package com.future.service.Impl;

import com.future.allUtils.utils.CacheClient;
import com.future.domain.vo.QuestionnaireVO;
import com.future.mapper.QuestionnaireMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import static com.future.allUtils.constants.RedisCacheConstants.QUESTIONNAIRE_INFO_PREFIX;

@Service
public class ExportService {

    @Resource
    private QuestionnaireMapper questionnaireMapper; // MyBatis Mapper

    @Resource
    private CacheClient cacheClient;


    // 导出Word
    public void exportWord(HttpServletResponse response, Long questionnaireId) throws IOException {
        try (XWPFDocument document = new XWPFDocument()) {
            QuestionnaireVO questionnaireVO = cacheClient.queryWithLogicalExpire(QUESTIONNAIRE_INFO_PREFIX, questionnaireId, QuestionnaireVO.class,
                    id -> questionnaireMapper.selectQuestionnaireById(id),
                    7L, TimeUnit.DAYS);
            if(questionnaireVO == null){
                questionnaireVO = questionnaireMapper.selectQuestionnaireById(questionnaireId);
                if (questionnaireVO != null) {
                    cacheClient.setWithLogicalExpire(QUESTIONNAIRE_INFO_PREFIX+questionnaireId,questionnaireVO,7L, TimeUnit.DAYS);
                }
            }
            if (questionnaireVO == null) {
                return;
            }
            // 创建标题
            XWPFParagraph title = document.createParagraph();
            title.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun titleRun = title.createRun();
            titleRun.setText(questionnaireVO.getTitle());
            titleRun.setBold(true);
            titleRun.setFontSize(20);
            // 填充数据
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText("问卷标题：" + questionnaireVO.getTitle());
            run.setBold(true);  //文本加粗
            run.setFontSize(20);
            // 创建表格
            XWPFTable table = document.createTable();
            // 设置表头
            XWPFTableRow headerRow = table.getRow(0);
            headerRow.getCell(0).setText("ID");
            headerRow.addNewTableCell().setText("标题");
            headerRow.addNewTableCell().setText("发布日期");





            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=articles.docx");

            // 写入响应流
            document.write(response.getOutputStream());
        }
    }

    // 导出PDF
    public void exportPdf(HttpServletResponse response, QuestionnaireVO questionnaireVO) throws DocumentException, IOException {
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            PdfWriter.getInstance((com.itextpdf.text.Document) document, baos);
            document.open();

            // 添加标题
            Font titleFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
            Paragraph title = new Paragraph("文章数据报告", titleFont);
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            document.add(Chunk.NEWLINE);

            // 创建表格
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100);

            // 表头
            Stream.of("ID", "标题", "发布日期")
                    .forEach(header -> {
                        PdfPCell cell = new PdfPCell(new Phrase(header));
                        cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                        table.addCell(cell);
                    });

            // 填充数据


            document.add(table);
            document.close();

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=articles.pdf");
            response.getOutputStream().write(baos.toByteArray());
        }
    }
}